#include "Connector.h"
#include "Common.h"
#ifdef WS_SSL
#include "root_certificates.hpp"
#endif
namespace wsbus {

	Connector::Connector(const std::string &host, const std::string &port)
	{
#ifdef WS_SSL
		load_root_certificates(sslctx_);
		impl_ = std::make_shared<ConnectorImpl>(ioc_, sslctx_, host, port);
#else
		impl_ = std::make_shared<ConnectorImpl>(ioc_, host, port);
#endif
	}

	Connector::~Connector()
	{
		if (!ioc_.stopped()) {
			ioc_.stop();
		}

		if (thread_.joinable()) {
			thread_.join();
		}
	}

	void Connector::connect()
	{
		thread_ = std::move(std::thread([&]() { 
			impl_->run();
			ioc_.run(); 
		}));
	}

	void Connector::reconnect()
	{
		std::string host = impl_->host();
		std::string port = impl_->port();
		auto handleCallback = impl_->getHandleCallback();
#ifdef WS_SSL
		load_root_certificates(sslctx_);
		impl_ = std::make_shared<ConnectorImpl>(ioc_, sslctx_, host, port);
#else
		impl_.reset(new ConnectorImpl(ioc_, host, port));
#endif
		impl_->setHandleCallback(handleCallback);
		runMainContext([this]() { impl_->run(); });
	}

	void Connector::setHandleCallback(const ConnectorImpl::HandleCallback &cb)
	{
		impl_->setHandleCallback(cb);
	}

	void Connector::post(const BufferPtr &msg)
	{
		impl_->post(msg);
	}

	time_t Connector::lastWriteMessageTime() const
	{
		return impl_->lastWriteMessageTime();
	}

	void Connector::runMainContext(const std::function<void()> &cb)
	{
		ioc_.post(cb);
	}
}